package com.zyx.concurrentdemo.c06cas;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.LongAdder;
import java.util.function.Consumer;
import java.util.function.Supplier;

/**
 * @author Yaxi.Zhang
 * @since 2021/10/18 11:59
 * desc: 使用LongAdder进行累加的案例
 */
@Slf4j(topic = "c.TestLongAdder")
@SuppressWarnings({"AlibabaAvoidManuallyCreateThread", "AlibabaUndefineMagicConstant"})
public class TestLongAdder {

    public static void main(String[] args) {
        // 普通的AtomicLong
        for (int i = 0; i < 5; i++) {
            demo(
                    () -> new AtomicLong(0),
                    AtomicLong::getAndIncrement
            );
        }

        System.out.println("=====>>>>> seperate");

        // 使用 LongAdder 进行累加操作, 性能显著提高
        for (int i = 0; i < 5; i++) {
            demo(
                    LongAdder::new,
                    LongAdder::increment
            );
        }

    }

    private static <T> void demo(Supplier<T> adderSupplier, Consumer<T> operation) {
        T adder = adderSupplier.get();
        List<Thread> threads = new ArrayList<>();
        // 4 个线程, 每人累加 50 万
        for (int i = 0; i < 4; i++) {
            threads.add(new Thread(() -> {
                for (int j = 0; j < 500000; j++) {
                    operation.accept(adder);
                }
            }));
        }
        long start = System.nanoTime();
        threads.forEach(Thread::start);
        threads.forEach(t -> {
            try {
                t.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        long end = System.nanoTime();
        System.out.println(adder + " cost:" + (end - start) / 1000_000);
    }

}
